import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

interface PathSuggestion {
  path: string;
  name: string;
  isDirectory: boolean;
}

// 检测路径触发上下文
function detectPathContext(model: any, position: any): { 
  isPathContext: boolean; 
  quotedPath: boolean; 
  triggerChar: string;
  basePath: string;
  currentInput: string;
  partialInput: string;
  completedPath: string;
} {
  const lineText = model.getLineContent(position.lineNumber);
  const textBefore = lineText.substring(0, position.column - 1);
  
  // 更精确的路径触发模式，避免误触发
  const patterns = [
    /import\s+.*?from\s+['"]([^'"]*?)$/,     // import ... from "path"
    /require\(['"]([^'"]*?)$/,               // require("path")
    /import\(['"]([^'"]*?)$/,                // import("path")
    /src\s*=\s*['"]([^'"]*?)$/,              // src="path"
    /href\s*=\s*['"]([^'"]*?)$/,             // href="path"
    /url\(['"]([^'"]*?)$/,                   // url("path")
  ];

  for (const pattern of patterns) {
    const match = textBefore.match(pattern);
    if (match) {
      const fullInput = match[1] || '';
      
      // 分离已完成的路径和正在输入的部分
      const lastSlashIndex = fullInput.lastIndexOf('/');
      let completedPath = '';
      let partialInput = fullInput;
      
      if (lastSlashIndex >= 0) {
        completedPath = fullInput.substring(0, lastSlashIndex + 1);
        partialInput = fullInput.substring(lastSlashIndex + 1);
      }
      
      return {
        isPathContext: true,
        quotedPath: true,
        triggerChar: textBefore.charAt(textBefore.length - 1),
        basePath: fullInput,
        currentInput: fullInput,
        partialInput,
        completedPath
      };
    }
  }

  return {
    isPathContext: false,
    quotedPath: false,
    triggerChar: '',
    basePath: '',
    currentInput: '',
    partialInput: '',
    completedPath: ''
  };
}

// 解析相对路径的基础目录
function resolveBasePath(currentFilePath: string, inputPath: string, completedPath: string, workspaceRoot: string): string {
  // 构建要搜索的目录路径
  let searchPath = '';
  
  if (completedPath.startsWith('/')) {
    // 绝对路径，基于工作区根目录
    searchPath = workspaceRoot + completedPath;
  } else if (completedPath.startsWith('./') || completedPath.startsWith('../') || completedPath.includes('/')) {
    // 相对路径，基于当前文件目录
    const currentDir = currentFilePath.substring(0, currentFilePath.lastIndexOf('/'));
    searchPath = currentDir + '/' + completedPath;
  } else {
    // 没有路径分隔符，在当前文件目录或工作区根目录搜索
    if (currentFilePath) {
      searchPath = currentFilePath.substring(0, currentFilePath.lastIndexOf('/'));
    } else {
      searchPath = workspaceRoot;
    }
  }
  
  // 规范化路径
  return searchPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
}

// 规范化文件系统路径，修复 Windows 盘符被错误加前导斜杠的情况
function normalizeFsPath(p: string): string {
  if (/^\/[A-Za-z]:/.test(p)) {
    return p.slice(1);
  }
  return p;
}

// 获取目录列表
// 添加缓存和防抖机制
let lastCallPath = '';
let lastCallTime = 0;
const DEBOUNCE_MS = 100;

async function getDirectoryListing(api: any, path: string): Promise<PathSuggestion[]> {
  const normalized = normalizeFsPath(path);
  const now = Date.now();
  
  // 防止短时间内重复调用相同路径
  if (normalized === lastCallPath && (now - lastCallTime) < DEBOUNCE_MS) {
    return [];
  }
  
  lastCallPath = normalized;
  lastCallTime = now;
  
  try {
    const entries = await api.rpc.invoke('fs_read_dir', { path: normalized }) as any[];
    if (!Array.isArray(entries)) return [];
    
    return entries.map(entry => ({
      path: entry.path || '',
      name: entry.name || (entry.path || '').split(/[\\/]/).pop() || '',
      isDirectory: entry.is_dir || false
    }));
  } catch (error) {
    console.warn('Failed to read directory:', normalized, error);
    return [];
  }
}

export function activate(context: any, api: any) {
  console.log('Activating path completion plugin...');

  // 支持的语言
  const supportedLanguages = [
    'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 
    'html', 'css', 'scss', 'less', 'json', 'markdown', 'vue'
  ];

  // 为每种语言注册路径补全
  supportedLanguages.forEach(languageId => {
    // 传统补全面板
    const completionDisposable = api.languages.registerCompletionProvider(languageId, {
      triggerCharacters: ['/', '.', '"', "'"],
      
      // 在 provideCompletionItems 中
      async provideCompletionItems(model: any, position: any) {
        const context = detectPathContext(model, position);
        if (!context.isPathContext) return { suggestions: [] };
      
        const currentFilePath = model.uri?.path || '';
        const workspaceRoot = api.workspace.rootPath || '';
        
        const basePath = resolveBasePath(currentFilePath, context.currentInput, context.completedPath, workspaceRoot);
        const listings = await getDirectoryListing(api, basePath);
      
        // 根据部分输入过滤结果
        const filteredListings = listings.filter(item => 
          context.partialInput === '' || 
          item.name.toLowerCase().startsWith(context.partialInput.toLowerCase())
        );
      
        const word = model.getWordUntilPosition(position);
        const range: monaco.IRange = {
          startLineNumber: position.lineNumber,
          startColumn: position.column - context.partialInput.length,
          endLineNumber: position.lineNumber,
          endColumn: position.column,
        };
      
        const suggestions: monaco.languages.CompletionItem[] = filteredListings.map(item => ({
          label: item.name,
          kind: item.isDirectory 
            ? monaco.languages.CompletionItemKind.Folder 
            : monaco.languages.CompletionItemKind.File,
          insertText: item.name + (item.isDirectory ? '/' : ''),
          detail: item.isDirectory ? '文件夹' : '文件',
          documentation: `路径: ${item.path}`,
          range,
          sortText: item.isDirectory ? `0_${item.name}` : `1_${item.name}`,
        }));
      
        return { suggestions };
      }
    });
    context.subscriptions.push(completionDisposable);

    // 内联补全（Ghost Text）
    // 内联补全（Ghost Text）
    const inlineCompletionDisposable = api.languages.registerInlineCompletionsProvider(languageId, {
      async provideInlineCompletions(model: any, position: any) {
        const context = detectPathContext(model, position);
        if (!context.isPathContext) return { items: [] };
  
        const currentFilePath = model.uri?.path || '';
        const workspaceRoot = api.workspace.rootPath || '';
        
        const basePath = resolveBasePath(currentFilePath, context.currentInput, context.completedPath, workspaceRoot);
        const listings = await getDirectoryListing(api, basePath);
        
        const items: monaco.languages.InlineCompletion[] = [];
  
        // 找到最佳匹配项
        const bestMatch = listings.find(item => 
          context.partialInput === '' || 
          item.name.toLowerCase().startsWith(context.partialInput.toLowerCase())
        );
  
        if (bestMatch && context.partialInput !== bestMatch.name) {
          const remaining = bestMatch.name.substring(context.partialInput.length);
          if (remaining) {
            items.push({
              insertText: remaining + (bestMatch.isDirectory ? '/' : ''),
              range: {
                startLineNumber: position.lineNumber,
                startColumn: position.column,
                endLineNumber: position.lineNumber,
                endColumn: position.column,
              }
            });
          }
        }
  
        return { items };
      },
      
      // 添加 Monaco Editor 期望的 freeInlineCompletions 方法
      freeInlineCompletions(completions: any) {
        // 目前没有需要释放的资源，保持 no-op，避免 Monaco 在回收时抛错
      }
    });
    context.subscriptions.push(inlineCompletionDisposable);
  });

  // 注册命令
  const commandDisposable = api.commands.registerCommand('pathCompletion.refreshCache', () => {
    api.window.showInformationMessage('路径补全缓存已刷新');
  });
  context.subscriptions.push(commandDisposable);

  console.log('Path completion plugin activated successfully!');
}

export function deactivate() {
  console.log('Deactivating path completion plugin...');
}